<template>
  <div class="adminAdd">
    <a-form-model
      ref="ruleForm"
      :model="ruleForm"
      v-bind="layout"
      :rules="rules"
    >
      <a-form-model-item
        label="商品名称"
        prop="name"
        :labelCol="{ span: 5 }"
        :wrapperCol="{ span: 12 }"
      >
        <a-input v-model="ruleForm.name" type="text" autocomplete="off" />
      </a-form-model-item>
      <a-form-model-item
        label="商品描述"
        prop="desc"
        :labelCol="{ span: 5 }"
        :wrapperCol="{ span: 12 }"
      >
        <a-input v-model="ruleForm.desc" type="text" autocomplete="off" />
      </a-form-model-item>
      <a-form-model-item
        label="分类"
        :labelCol="{ span: 5 }"
        :wrapperCol="{ span: 12 }"
        required
      >
        <a-cascader
          :options="options"
          placeholder="请选择分类"
          @change="onChange"
          :default-value="ruleForm.classify_id"
          :value="ruleForm.classify_id"
        />
      </a-form-model-item>
      <a-form-model-item
        label="价格"
        prop="price"
        :labelCol="{ span: 5 }"
        :wrapperCol="{ span: 12 }"
      >
        <a-input
          v-model="ruleForm.price"
          type="number"
          autocomplete="off"
          :min="0"
          @change="numChange('price')"
        />
      </a-form-model-item>
      <a-form-model-item
        label="优惠价格"
        prop="sale_price"
        :labelCol="{ span: 5 }"
        :wrapperCol="{ span: 12 }"
      >
        <a-input
          v-model="ruleForm.sale_price"
          type="number"
          autocomplete="off"
          :min="0"
          @change="numChange('sale_price')"
        />
      </a-form-model-item>
      <a-form-model-item
        label="图片"
        :labelCol="{ span: 5 }"
        :wrapperCol="{ span: 12 }"
      >
        <div class="clearfix">
          <a-upload
            :action="UPLOADGOODS"
            :headers="headers"
            list-type="picture-card"
            :multiple="true"
            :default-file-list="fileList"
            class="upload-list-inline"
            @preview="handlePreview"
            @change="handleChange"
            :data="uploadData"
            :remove="remove"
          >
            <a-icon type="plus" />
            <div class="ant-upload-text">上传图片</div>
          </a-upload>
          <a-modal
            :visible="previewVisible"
            :footer="null"
            @cancel="handleCancel"
            :zIndex="1001"
          >
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
      </a-form-model-item>

      <a-form-model-item
        label="库存数量"
        prop="stock_num"
        :labelCol="{ span: 5 }"
        :wrapperCol="{ span: 12 }"
      >
        <a-input
          v-model.number="ruleForm.stock_num"
          type="number"
          :min="0"
          @change="numChange('stock_num')"
        />
      </a-form-model-item>

      <a-form-model-item
        label="商品详情"
        prop="rich_text"
        :labelCol="{ span: 5 }"
        :wrapperCol="{ span: 15 }"
      >
        <wang-editor
          v-model="ruleForm.rich_text"
          :disabled="wangDisabled"
        ></wang-editor>
      </a-form-model-item>
      <a-form-model-item :wrapper-col="{ span: 14, offset: 10 }">
        <a-button type="primary" @click="submitForm('ruleForm')">{{
          id ? '修改' : '添加'
        }}</a-button>
        <a-button style="margin-left: 10px" @click="resetForm('ruleForm')"
          >重置</a-button
        >
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
import wangEditor from '@/pages/components/wangEditor/index.vue';
import getCookie from '@/utils/getCookie';
import { UPLOADGOODS } from '@/services/shopApi/api';
import { mapState } from 'vuex';
import {
  goodsClassify,
  updateGood,
  addGood,
  goodDetails,
} from '@/services/shopApi/dataSource';
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default {
  components: { wangEditor },
  props: ['info'],
  data() {
    return {
      // cascaderDefault: [],
      uploadData: { type: 1 },
      ruleForm: {
        name: '',
        // 分类id
        classify_id: [],
        price: '',
        // 库存数量
        stock_num: '',
        // 图片id
        photoArr: [],
        photo_ids: '',
        // 富文本
        rich_text: '',
      },
      rules: {
        name: [{ required: true, message: '请输入商品名', trigger: 'blue' }],
        // classify:[
        //   { required: true, message: '请选择分类', trigger: 'change'}
        // ],
        price: [{ required: true, message: '请输入价格', trigger: 'change' }],
        stock_num: [
          { required: true, message: '请输入库存量', trigger: 'change' },
        ],
      },
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      options: [],
      previewVisible: false,
      previewImage: '',
      fileList: [],
      UPLOADGOODS: '',
      id: null,
      // 富文本
      wangDisabled: false,
      headers: {},
    };
  },
  mounted() {
    this.UPLOADGOODS = UPLOADGOODS;
    this.headers['authorization'] = getCookie('Authorization');
    this.info ? (this.id = this.info.id) : (this.id = null);
    if (this.id) {
      this.getGoodsDetail();
    } else {
      this.getClassify() && this.getClassify();
    }
  },
  methods: {
    // 获取商品信息
    async getGoodsDetail() {
      await this.getClassify();
      goodDetails(this.id)
        .then((res) => {
          const result = res.result;
          // 分类
          const classifyArr = result.classify_ids.toString().split(',');
          let hy666 = classifyArr.map((r) => {
            return parseInt(r);
          });
          // 判断是否存在图片
          if (result.s_goods_photos && result.s_goods_photos.length) {
            result.s_goods_photos.map((r) => {
              this.fileList.push({
                uid: r.id,
                status: 'done',
                url: r.path,
                name: 'image.png',
              });
            });
          }
          this.ruleForm = {
            id: result.id,
            name: result.name,
            desc: result.desc,
            // 分类id
            classify_id: hy666,
            price: result.price,
            sale_price: result.sale_price,
            project_id: result.project_id,
            // 库存数量
            stock_num: result.stock_num,
            // 图片id
            photoArr: result.photo_ids.toString().split(','),
            photo_ids: result.photo_ids,
            rich_text: result.rich_text || '',
          };
          //
        })
        .catch((err) => {});
    },
    // 数值的变化
    numChange(msg, e) {
      e = window.event || e;
      this.ruleForm[msg] = Math.abs(e.target.value);
    },
    submitForm() {
      if (this.ruleForm.photoArr.length == 0) {
        this.$message.error('请上传商品图片');
        return;
      }
      if (this.ruleForm.classify_id == '') {
        this.$message.error('请选择商品分类');
        return;
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          //
          this.ruleForm.photo_ids = this.ruleForm.photoArr.join(',');
          let resdata = JSON.parse(JSON.stringify(this.ruleForm));
          resdata.classify_id = resdata.classify_id.join(',');
          // 编辑

          if (this.id) {
            updateGood(resdata)
              .then((res) => {
                this.$message.success(res.msg);
                this.$emit('close');
              })
              .catch((err) => {
                this.$message.error(err.msg);
              });
          }
          //添加
          else {
            addGood(resdata)
              .then((res) => {
                this.$message.success(res.msg);
                sessionStorage.removeItem('goodsList');
                this.$router.push('/shop/goods/goodsList');
              })
              .catch((err) => {
                this.$message.error(err.msg);
              });
          }
        } else {
          this.$message.error('提交错误,请填写必填项');
          return false;
        }
      });
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    onChange(value) {
      this.ruleForm.classify_id = value;
    },
    handleCancel(res) {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }

      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    // 删除图片
    remove(res) {
      // w_goods.upDataGoods(this.ruleForm).then(res => {
      //
      // })
      this.ruleForm.photoArr.map((r, index) => {
        if (res.uid == r) {
          this.ruleForm.photoArr.splice(index, 1);
          // 更新图片
          updateGood(this.ruleForm).then((res) => {});
        }
      });
      //
    },
    // 图片上传状态改变
    handleChange(res) {
      // 上传完成
      if (res.file.status === 'done') {
        this.ruleForm.photoArr.push(res.file.response.result.id);
      }
      this.fileList = res.fileList;
    },

    // 获取所有商品分类
    async getClassify() {
      goodsClassify()
        .then((res) => {
          const data = res.result;

          let temp_obj = {};
          data.forEach((val) => {
            val.value = val.id;
            val.key = val.id;
            val.label = val.name;
            temp_obj[val.parent_id]
              ? temp_obj[val.parent_id].push(val)
              : (temp_obj[val.parent_id] = [val]);
          });

          function melon(parent_id = 0) {
            // eslint-disable-next-line no-prototype-builtins
            if (temp_obj.hasOwnProperty(parent_id)) {
              let temp_arr = temp_obj[parent_id];
              temp_arr.forEach((val, index) => {
                let second_arr = melon(val.id);
                second_arr.length && (temp_arr[index]['children'] = second_arr);
              });
              return temp_arr;
            } else {
              return [];
            }
          }
          if (!this.options.length) {
            this.options = this.options.concat(melon());
          }
        })
        .catch((err) => {});
    },
  },
  beforeRouteUpdate(next) {
    this.ruleForm.classify_id = [];
    next();
  },
  computed: {
    ...mapState('account', ['user']),
  },
  watch: {
    // $route() {
    //   // beforeRouteUpdate (to, from, next) {
    //   this.$set(this.ruleForm, "classify_id", [])
    //   // 在当前路由改变，但是该组件被复用时调用
    //   // 举例来说，对于一个带有动态参数的路径 /foo/:id，在 /foo/1 和 /foo/2 之间跳转的时候，
    //   // 由于会渲染同样的 Foo 组件，因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    //   // 可以访问组件实例 `this`
    //   //   },
    // }
  },
};
</script>

<style scoped lang="scss">
.upload {
  width: 98px;
  height: 98px;
  font-size: 15px;
  .upload-list-inline {
    //       .ant-upload-list-item {
    //   float: left;
    //   width: 200px;
    //   margin-right: 8px;
    // }
    .ant-upload-animate-enter {
      animation-name: uploadAnimateInlineIn;
    }
    .ant-upload-animate-leave {
      animation-name: uploadAnimateInlineOut;
    }
  }
}

.adminAdd {
  .specCon {
    border: 1px solid #ccc;
    padding: 15px;
    .spec {
      .title {
        font-size: 16px;
        font-weight: bold;
        position: relative;
        .anticon {
          cursor: pointer;
          &:hover {
            background-color: #ccc;
            border-radius: 50%;
          }
        }
      }
      .block {
        display: flex;
        > div {
          border: 1px solid #ccc;
          border-radius: 4px;
          padding: 0px 5px;
          margin-right: 20px;
          .anticon {
            cursor: pointer;
            &:hover {
              background-color: #ccc;
              border-radius: 50%;
            }
          }
          &.add {
            box-sizing: content-box;
            width: 160px;
            height: 40px;
            border: 1px solid #ccc;
            display: flex;
            align-items: center;
            input {
              width: 118px;
              height: 40px;
              line-height: 40px;
            }
            span {
              flex: none;
              width: 50px;
              height: 40px;
              line-height: 40px;
              text-align: center;
              background-color: #ccc;
              border-radius: 0 4px 4px 0;
              cursor: pointer;
            }
          }
        }
      }
    }
  }
}
</style>
